package com.woniuxy.classdeans.controller;

import com.woniuxy.classdeans.service.GradeInfoService;
import com.woniuxy.classdeans.service.KonwledgeAnalyzeService;
import com.woniuxy.commons.entity.*;
import com.woniuxy.commons.entity.wyh.GradeInfo;
import com.woniuxy.commons.entity.wyh.Knowledgepoint;
import com.woniuxy.commons.entity.wyh.SchoolAndScore;
import com.woniuxy.commons.enums.SubjectEnum;
import com.woniuxy.commons.utils.TimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @Author weizihan
 * @Date 2020/7/24 2020/7/24
 * @Description 数据分析
 * @Since version-1.0
 */
@RestController
@RequestMapping("/analyze")
public class KnowledgeAnalyzeController {
    @Autowired
    private KonwledgeAnalyzeService konwledgeAnalyzeService;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private GradeInfoService GradeInfoService;

    //获取全部学校
    @RequestMapping("/schoolAll")
    public ResponseResult<List<SchoolInfo>> schoolAll() {
        List<SchoolInfo> schoolInfos = konwledgeAnalyzeService.schoolAll();
        return new ResponseResult<List<SchoolInfo>>().setMessage("学校获取成功").setCode(200).setData(schoolInfos);
    }

    //获取所有的学期---20xx届学生
    @RequestMapping("/semesterAll")
    public ResponseResult<List<GradeInfo>> semesterAll() {
        String gradeType = "高三";
        List<GradeInfo> gradeInfos = konwledgeAnalyzeService.semesterAll(gradeType);
        //System.out.println(gradeInfos);
        return new ResponseResult<List<GradeInfo>>().setMessage("届获取成功").setCode(200).setData(gradeInfos);
    }

    //获取所有的科目
    @RequestMapping("/subjectAll")
    public ResponseResult<List<String>> subjectAll() {
        List<String> lists = new ArrayList<String>();
        SubjectEnum[] enumConstants = SubjectEnum.class.getEnumConstants();
        for (SubjectEnum s : enumConstants
        ) {
            lists.add(s.getChineses());
        }
        return new ResponseResult().setMessage("科目获取成功").setCode(200).setData(lists);
    }

    //获取科目对应的知识点
    @RequestMapping("/knowledgeAll/{subject}")
    public ResponseResult<List<Knowledgepoint>> knowledgeAll(@PathVariable("subject") String subject) {
        List<Knowledgepoint> knowledgepoints = konwledgeAnalyzeService.knowledgesAll(subject);
        return new ResponseResult().setMessage("对应知识点获取成功").setCode(200).setData(knowledgepoints);
    }


    //获取本校五年的分数线情况
    @RequestMapping("/All/{schoolId}/{semesterId}/{subjectsId}/{knowledgeId}")
    public ResponseResult<Set<SchoolAndScore>> All(
            HttpServletRequest req, @PathVariable("schoolId") String schoolId, @PathVariable("semesterId") String semesterId, @PathVariable("subjectsId") String subjectsId, @PathVariable("knowledgeId") String knowledgeId) {
        System.out.println(schoolId + ":" + semesterId + ":" + subjectsId + ":" + knowledgeId);
        long beginTime = System.currentTimeMillis();
        ResponseResult<Set<SchoolAndScore>> result = new ResponseResult<Set<SchoolAndScore>>().setCode(400).setMessage("数据返回错误");
        //存储总人数和对应得年份
        List<Scores> scores = new ArrayList<>(10);
        //年纪id
        List<GradeInfo> gaIds = new ArrayList<>();
        //获取班级id
        List<Integer> sids = new ArrayList<>();
        //获取学生id
        List<Integer> stuids = new ArrayList<>();
        //获取5年考试的总人数
        Map<Integer, Integer> studentExaminations = new HashMap<>();
        //通过token获取用户所在的学校id
/*        String refreshToken = req.getHeader("refreshToken");
        Map<Object,Object> map= redisTemplate.opsForHash().entries(refreshToken);
        Integer id = (Integer)map.get("rid");*/
        //通过获取的年级主任id获取学校的id 微数据id = 3
        GradeInfo gi = GradeInfoService.getByGdid(3);
        //   System.out.println(gi);

        if (gi.getShoolid() == null)
            return result;

        //获取5年内的ga_Id---timeString获取当前年份+高三获取所有高三的年纪id
        String timeString = TimeUtil.getTimeString(new Date().getTime()).split("-")[0];
        //获取时间
        gaIds = GradeInfoService.getBySheetStudentNo(new GradeInfo().setGradeType("高三").setBeginyear(Integer.parseInt(timeString)));
        for (int i = 0; i < gaIds.size(); i++) {
            //通过获取年纪获取到对应得班级信息
            List<Integer> tcIds = konwledgeAnalyzeService.findGaIdBytmId(gaIds.get(i).getGaId());
            for (int j = 0; j < tcIds.size(); j++) {
                sids.add(tcIds.get(j));
            }
        }
        //通过获取的班级id和学校id找到学生id
        for (int i = 0; i < sids.size(); i++) {
            List<Integer> stuid = konwledgeAnalyzeService.findStuidByClassIdAndSchoolId(new StudentInfo().setClassid(sids.get(i)).setSchoolid(gi.getShoolid()));
            for (int j = 0; j < stuid.size(); j++) {
                stuids.add(stuid.get(j));
            }
        }

        //  System.out.println(stuids);
        //通过学生id获取对应得分数及他所考试的年份
        for (int i = 0; i < stuids.size(); i++) {
            Double studnetScores = konwledgeAnalyzeService.findStudentIdByScore(stuids.get(i));
            StudentInfo studentPeriod = konwledgeAnalyzeService.findStudentIdByDate(new StudentInfo().setStuid(stuids.get(i)));
            scores.add(new Scores().setYear(studentPeriod.getTeamInfo().getGradeInfo().getBeginyear()).setScores(studnetScores).setSchool(gi.getShoolid()));

        }
        //通过年纪id来查询对应得考试的人数
        for (int i = 0; i < gaIds.size(); i++) {
            Integer studentExamination = konwledgeAnalyzeService.findStudentExamination(gaIds.get(i).getGaId());
            studentExaminations.put(gaIds.get(i).getBeginyear(), studentExamination / 4);
            //  System.out.println(studentExamination/4);
        }

        //System.out.println(calculate(studentExaminations,scores));;
        if (schoolId != null && !schoolId.equals("schoolId")) {
            Integer sid = Integer.parseInt(schoolId);
            if (sid != gi.getShoolid()) {
                //在答题卡表中获取所有的sid学校考试的学生id并且用set去重
                Set<Integer> setStudents = konwledgeAnalyzeService.findSidByStudentId(sid);
                for (Integer s : setStudents
                ) {
                    //查询分数
                    Double sScore = konwledgeAnalyzeService.findSidStudentScore(s);
                    scores.add(new Scores().setYear(2020).setScores(sScore).setSchool(sid));
                }
                //获取人数
                Integer sNumber = setStudents.size();
                //获取学校名字
        /*    String schoolName = konwledgeAnalyzeService.findSchoolNameBySid(sid);
            System.out.println(schoolName);*/
                studentExaminations.put(sid, sNumber);

            }
        }
        long endTime = System.currentTimeMillis();
        System.out.println(scores);
        System.out.println(endTime - beginTime + "***************************************************************");
        System.out.println(calculate(studentExaminations, scores));
        return result.setCode(200).setMessage("ok").setData(calculate(studentExaminations, scores));
    }

    //计算5年来的本科率，专科率，重本率
    public Set<SchoolAndScore> calculate(Map<Integer, Integer> studentExaminations, List<Scores> scores) {
        //  System.out.println(scores);
        int heavynumber = 0;      //重本
        int regularnumber = 0;    //本科
        int specialtynumber = 0;  //专科
        int ontPassnumber = 0;    //未通过
        double ontPass = 0;        //未通过率
        double heavy = 0;         //重本升学率
        double regular = 0;       //本科升学率
        double specialty = 0;     //专科升学率
        int schoolId = 0;         //学校id
        //存储每一届学生升学率
        Set<SchoolAndScore> schoolAndScores = new TreeSet<>();
        //获取5年来的分数线
        List<ScoreLine> slist = konwledgeAnalyzeService.findScoreChart();
        for (int i = 0; i < slist.size(); i++) {
            int year = Integer.parseInt(slist.get(i).getYear());

            for (int j = 0; j < scores.size(); j++) {
                if (j + 1 < scores.size()) {
                    System.out.println(year + ":" + scores.get(j).getSchool() + ":" + scores.get(j + 1).getSchool());
                    if (year == scores.get(j).getYear() && scores.get(j).getSchool() == scores.get(j + 1).getSchool()) {
                        schoolId = scores.get(j).getSchool();
                        //获取今年的分数本科率
                        if (scores.get(j).getScores() >= slist.get(i).getHeavy()) {
                            //重本人数++
                            heavynumber++;
                        } else if (scores.get(j).getScores() < slist.get(i).getHeavy() && scores.get(j).getScores() >= slist.get(i).getRegular()) {
                            //本科人数++
                            regularnumber++;
                        } else if (scores.get(j).getScores() < slist.get(i).getRegular() && scores.get(j).getScores() >= slist.get(i).getSpecialty()) {
                            //专科人数++
                            specialtynumber++;
                        } else if (scores.get(j).getScores() < slist.get(i).getSpecialty()) {
                            //未通过人数++
                            ontPassnumber++;
                        }
                    }
                }
            }
            //计算出升学率
            for (Map.Entry<Integer, Integer> m : studentExaminations.entrySet()) {
                if (m.getKey() == year) {
                    heavy = (double) heavynumber / m.getValue();
                    regular = (double) regularnumber / m.getValue();
                    specialty = (double) specialtynumber / m.getValue();
                    ontPass = (double) ontPassnumber / m.getValue();
                }
                //  System.out.println(m.getValue()+":"+m.getKey());
            }
            schoolAndScores.add(
                    new SchoolAndScore()
                            .setHeavynumber(heavynumber)
                            .setRegularnumber(regularnumber)
                            .setSpecialtynumber(specialtynumber)
                            .setOntPassnumber(ontPassnumber)
                            .setGrade(year)
                            .setHeavy(heavy)
                            .setRegular(regular)
                            .setSpecialty(specialty)
                            .setOntPass(ontPass)
                            .setSchoolId(schoolId));
            heavynumber = 0;
            regularnumber = 0;
            specialtynumber = 0;
            ontPassnumber = 0;
            heavy = 0;
            regular = 0;
            specialty = 0;
            ontPass = 0;
            schoolId = 0;
        }
        return schoolAndScores;
    }
}
